package com.hmdp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Result selectType() {
        String JsonShopType = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        if(!StringUtils.isEmpty(JsonShopType)){
            List<ShopType> shopTypes = JSONUtil.toList(JsonShopType, ShopType.class);
            return Result.ok(shopTypes);
        }
        //查数据库，并写入缓存
        List<ShopType> ShopType = query().orderByAsc("sort").list();
        if(ObjectUtil.isEmpty(ShopType)){
            return Result.fail("数据库没有商户类型");
        }
        JsonShopType = JSONUtil.toJsonStr(ShopType);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,JsonShopType);
        return Result.ok(ShopType);
    }
}
